﻿// MIT License
//
// Copyright (c) 2021-present zuohuaijun, Daming Co.,Ltd and Contributors
//
// 电话/微信：18020030720 QQ群1：87333204 QQ群2：252381476

using Admin.Net.InformationPlatform.Entity;
using Admin.Net.InformationPlatform.Entity.Order;
using Admin.NET.Application.Const;
using Admin.NET.Core.Service;
using Aliyun.Acs.Core.Http;
using Aliyun.OSS.Util;
using AngleSharp.Dom;
using Castle.Components.DictionaryAdapter.Xml;
using COSXML.Network;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Masuit.Tools;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Office.Interop.Word;
using Nancy.Json;
using Nest;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NPOI.OpenXmlFormats.Spreadsheet;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Numeric;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinUserInfoBatchGetRequest.Types;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.WxaBusinessPerformanceBootResponse.Types.Data.Types;
using HttpClient = System.Net.Http.HttpClient;

namespace Admin.Net.InformationPlatform.Service.Order.Dto
{
    /// <summary>
    /// 下单平台
    /// </summary>
    [ApiDescriptionSettings(groups: "Order", Name = "OA审核", Tag = "OA审核", Order = 200)]

    public class CustomerOAService : IDynamicApiController, ITransient
    {
        private static readonly string APPID = @"jUhwUM2KGakoT05z4y9j+7hZp3Cl7kF/1WsYcI5YyhIcVGrxMqi6gQAoHyY3OvhE";
        private readonly SysUserRoleService _sysUserRoleService;
        /// <summary>
        /// 单例数据链接
        /// </summary>
        ISqlSugarClient db;
        /// <summary>
        /// T100数据库
        /// </summary>
        private static SqlSugarProvider _T100Db;
        private SqlSugarProvider _SjDb;
        private SqlSugarProvider _plm;
        private static SqlSugarProvider _Dilon;
        /// <summary>
        /// 用户信息
        /// </summary>
        static TokenUser _User;
        public CustomerOAService(ISqlSugarClient db, SysUserRoleService sysUserRoleService)
        {

            // 获取 `Jwt` 存储的信息 企业编号与据点信息
            _User = Util.SjCommonUtil.GetT100UserTokenInfo(_T100Db, _Dilon);

        }
        [AllowAnonymous]
        public async System.Threading.Tasks.Task RegistAsync()
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            string cpk = Convert.ToBase64String(rsa.ExportCspBlob(false));
            // RequestBody requestBody = new FormBody.Builder().Build();

            StringContent requestBody = new StringContent("", Encoding.UTF8, "application/x-www-form-urlencoded");
            using System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();

            client.DefaultRequestHeaders.Add("appid", APPID);
            client.DefaultRequestHeaders.Add("cpk", cpk);
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "http://10.8.1.163:8989/api/ec/dev/auth/regist");
            request.Content = requestBody;

            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();

                OAResponse o = JsonConvert.DeserializeObject<OAResponse>(responseBody);
                var a = o.ToString();
                Console.WriteLine("注册" + o.ToString());
            }
            else
            {
                Console.WriteLine("请求失败");
            }



        }
        public static async  System.Threading.Tasks.Task<string> ApplyTokenAsync()
        {
     
            // 上一步注册时获取到的token
            string secret = "25513217-7c60-40b2-908c-df4ca6af7664";
            // 上一步获取到的spk
            string spk = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApJ6I6btW1vkEra/uJlckk/3+DQrAfAkzPrQXnft59DkWYb19YeJ+MN3Dl37Tv3XrmOU7nMJpspADFI0l1H+pLoWmF7s5txPX6m0IG+j0+laRKammQgxq771nh8iVnWZBBD6Jmf3AnAsSKSdC0VIXWwzV36N35VTr+3ukYlFTIZF4VcPq/O9VGj3f1Tj4U9T1zzSoy60SL94yNboOk43eHguDiXtSlKjg7mVDCCXcRjoqRlQJADxlvd2sP/KpsrN+P+l7j3YBSwam5Q7qVawaUXwST+DVbY5D0007ygIdNzXkonPvhBybOPQUGXQfeSeVjOqYWAoJLCWPF9R3eOU7xQIDAQAB";


            // 创建RSA实例
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            // 设置公钥
            rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(spk), out _);

            // 加密
            byte[] secretBytes = Encoding.UTF8.GetBytes(secret);
            byte[] encryptedBytes = rsa.Encrypt(secretBytes, false);
            string encryptSecret = Convert.ToBase64String(encryptedBytes);


            // 创建 HttpClient
            HttpClient httpClient = new HttpClient();

            // 构造请求头
            httpClient.DefaultRequestHeaders.Add("appid", APPID);
            httpClient.DefaultRequestHeaders.Add("time", (365 * 24 * 60 * 60).ToString());
            httpClient.DefaultRequestHeaders.Add("secret", encryptSecret);

            // 发送请求
            HttpResponseMessage response = await httpClient.PostAsync("http://10.8.1.163:8989/api/ec/dev/auth/applytoken", null);

            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                JObject jsonObject = JObject.Parse(responseContent);
                //获取到的TOKEN
                return (string)jsonObject["token"];  
            }
            else
            {
                throw Oops.Oh($"获取TOKEN失败");
            }

        }


        public static async System.Threading.Tasks.Task CreateOAAsync(FilingClient input)
        {
            string Token = await ApplyTokenAsync();
            OaWorkflowsModel oaWorkflowsModel = new OaWorkflowsModel();
            oaWorkflowsModel.workflowId = "1289";//流程ID
            //oaWorkflowsModel.RequestLevel = "0";
            oaWorkflowsModel.requestName = "客户报备流程-" + DateTime.Now.ToString("yyyy-MM-dd");
            oaWorkflowsModel.remark = "接口调用测试";
            Dictionary<string, object> map = new Dictionary<string, object>();
            map.Add("isnextflow", 1);
            map.Add("delReqFlowFaild", 1);
            map.Add("isVerifyPer", 0);
            oaWorkflowsModel.otherParams = map;
            //主表字段
            List<MainFiled> mainFileds = new List<MainFiled>();
            mainFileds.Add(new MainFiled { fieldName = "daeent", fieldValue = "8" });//企业编号
            mainFileds.Add(new MainFiled { fieldName = "daelorg", fieldValue = "SJGS" });//归属组织
            mainFileds.Add(new MainFiled { fieldName = "daestus", fieldValue = input.STATE.ToString() });//状态码
            mainFileds.Add(new MainFiled { fieldName = "xalcper", fieldValue = "017618" });//建立人员
            mainFileds.Add(new MainFiled { fieldName = "xalcdate", fieldValue = DateTime.Now.ToString("yyyy-MM-dd") });//建立时间
            //mainFileds.Add(new MainFiled { fieldName = "xaldocno", fieldValue = "N" });//客户编号
            //mainFileds.Add(new MainFiled { fieldName = "xalnote", fieldValue = "N" });//备注
            //mainFileds.Add(new MainFiled { fieldName = "xaladdr", fieldValue = "N" });//客户地址
            //mainFileds.Add(new MainFiled { fieldName = "xalcust", fieldValue = "N" });//报备渠道商
            mainFileds.Add(new MainFiled { fieldName = "xalattn", fieldValue = "017618" });//报备人
            mainFileds.Add(new MainFiled { fieldName = "xal001", fieldValue = input.CUSTOMERNAME });//客户公司全称
            mainFileds.Add(new MainFiled { fieldName = "xal002", fieldValue = input.TAXID });//客户公司税号
            //mainFileds.Add(new MainFiled { fieldName = "daestus", fieldValue = "N" });//所属区域
            oaWorkflowsModel.mainData = mainFileds;

     


            // 上一步获取到的spk
            string spk = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApJ6I6btW1vkEra/uJlckk/3+DQrAfAkzPrQXnft59DkWYb19YeJ+MN3Dl37Tv3XrmOU7nMJpspADFI0l1H+pLoWmF7s5txPX6m0IG+j0+laRKammQgxq771nh8iVnWZBBD6Jmf3AnAsSKSdC0VIXWwzV36N35VTr+3ukYlFTIZF4VcPq/O9VGj3f1Tj4U9T1zzSoy60SL94yNboOk43eHguDiXtSlKjg7mVDCCXcRjoqRlQJADxlvd2sP/KpsrN+P+l7j3YBSwam5Q7qVawaUXwST+DVbY5D0007ygIdNzXkonPvhBybOPQUGXQfeSeVjOqYWAoJLCWPF9R3eOU7xQIDAQAB";


            // 创建RSA实例
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            // 设置公钥
            rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(spk), out _);
            // 加密
            byte[] secretBytes = Encoding.UTF8.GetBytes("5970");
            byte[] encryptedBytes = rsa.Encrypt(secretBytes, false);
            string userid = Convert.ToBase64String(encryptedBytes);


            // 创建 HttpClient
            HttpClient httpClient = new HttpClient();

            // 构造请求头
            httpClient.DefaultRequestHeaders.Add("appid", APPID);
            httpClient.DefaultRequestHeaders.Add("token", Token);
            httpClient.DefaultRequestHeaders.Add("userid", userid);
            httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

            // 构建请求体设置请求头
            string requestBody = JsonConvert.SerializeObject(oaWorkflowsModel);
            var content = new StringContent(requestBody, Encoding.UTF8, "application/json");


            // 发送请求
            HttpResponseMessage response = await httpClient.PostAsync("http://10.8.1.163:8989/api/workflow/paService/doCreateRequest", content);

            if (response.IsSuccessStatusCode)
            {
                string responseContent = await response.Content.ReadAsStringAsync();
                JObject jsonObject = JObject.Parse(responseContent);
                //获取到的TOKEN
                // string token = (string)jsonObject["token"];

            }
            else
            {
                Console.WriteLine("Request failed: " + response.StatusCode);
            }
         
        }

    }
}
